package com.example.car;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.region.IoTDARegion;
import com.huaweicloud.sdk.iotda.v5.*;
import com.huaweicloud.sdk.iotda.v5.model.*;


public class CreateMessageSolution {


    public String downMessage(String deviceId, String downMessage) throws JsonProcessingException {
        String ak = "FRGD896V6XFNCRAVC4AM";
        String sk = "2THTLrdVT5vpx8pxXsOKRbVfORU2D7GOlfbmDk4i";

        ICredential auth = new BasicCredentials()
                .withAk(ak)
                .withSk(sk);

        IoTDAClient client = IoTDAClient.newBuilder()
                .withCredential(auth)
                .withRegion(IoTDARegion.valueOf("cn-north-4"))
                .build();
        CreateMessageRequest request = new CreateMessageRequest();
        request.withDeviceId("device1huaweiyun");
        DeviceMessageRequest body = new DeviceMessageRequest();
        body.withMessage(downMessage);
        request.withBody(body);
        String message = null;
        try {
            CreateMessageResponse response = client.createMessage(request);
            System.out.println(response.toString());
            String a = response.toString();
            message = a;
            return message;
        } catch (ConnectionException e) {
            e.printStackTrace();
        } catch (RequestTimeoutException e) {
            e.printStackTrace();
        } catch (ServiceResponseException e) {
            e.printStackTrace();
            JsonNode node = new ObjectMapper().readValue(e.toString(), JsonNode.class);
            JsonNode subNode = node.get(0);
            message = subNode.get("error_msg").asText();
            System.out.println(e.getHttpStatusCode());
            System.out.println(e.getErrorCode());
            System.out.println(e.getErrorMsg());
            return message;
        }
        return message;
    }
}
